package com.example.friend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.common.core.model.TableDataInfo;
import com.example.common.redis.service.RedisService;
import com.example.friend.elasticsearch.QuestionRepository;
import com.example.friend.manager.QuestionCacheManager;
import com.example.friend.mapper.QuestionMapper;
import com.example.friend.mapper.UserSubmitMapper;
import com.example.friend.model.question.Question;
import com.example.friend.model.question.dto.QuestionQueryDTO;
import com.example.friend.model.question.es.QuestionES;
import com.example.friend.model.question.vo.QuestionDetailVO;
import com.example.friend.model.question.vo.QuestionVO;
import com.example.friend.service.IQuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 功能描述:
 *
 * @author Lenovo
 * @date 2025/4/8
 */
@Service
public class QuestionServiceImpl implements IQuestionService {
    @Autowired
    private QuestionRepository questionRepository;
    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private QuestionCacheManager questionCacheManager;
    @Autowired
    private RedisService redisService;
    @Autowired
    private UserSubmitMapper userSubmitMapper;

    @Value("${question.hot.cache-time:30}")
    private Long hotQuestionCacheTime;
    
    private static final String HOT_QUESTION_KEY = "hot_question";
    
    @Override
    public TableDataInfo list(QuestionQueryDTO questionQueryDTO) {
        long count = questionRepository.count();
        if (count <= 0) {
            refreshQuestion();
        }
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        Pageable pageable = PageRequest.of(questionQueryDTO.getPageNum() - 1, questionQueryDTO.getPageSize(), sort);
        Integer difficulty = questionQueryDTO.getDifficulty();
        String keyword = questionQueryDTO.getKeyword();
        Page<QuestionES> questionESPage;
        if (difficulty == null && StrUtil.isEmpty(keyword)) {
            questionESPage = questionRepository.findAll(pageable);
        } else if (StrUtil.isEmpty(keyword)) {
            questionESPage = questionRepository.findQuestionByDifficulty(difficulty, pageable);
        } else if (difficulty == null) {
            questionESPage = questionRepository.findByTitleOrContent(keyword, keyword, pageable);
        } else {
            questionESPage = questionRepository.findByTitleOrContentAndDifficulty(keyword, keyword, difficulty, pageable);
        }
        long total = questionESPage.getTotalElements();
        if (total <= 0) {
            return TableDataInfo.empty();
        }
        List<QuestionES> questionESList = questionESPage.getContent();
        List<QuestionVO> questionVOList = BeanUtil.copyToList(questionESList, QuestionVO.class);
        return TableDataInfo.success(questionVOList, total);
    }

    @Override
    public QuestionDetailVO detail(Long questionId) {
        QuestionES questionES = questionRepository.findById(questionId).orElse(null);
        QuestionDetailVO questionDetailVO = new QuestionDetailVO();
        if (questionES != null) {
            BeanUtil.copyProperties(questionES, questionDetailVO);
            return questionDetailVO;
        }
        Question question = questionMapper.selectById(questionId);
        if (question == null) {
            return null;
        }
        refreshQuestion();
        BeanUtil.copyProperties(question, questionDetailVO);
        return questionDetailVO;
    }

    @Override
    public String preQuestion(Long questionId) {
        Long listSize = questionCacheManager.getListSize();
        if (listSize == null || listSize <= 0) {
            questionCacheManager.refreshCache();
        }
        return questionCacheManager.preQuestion(questionId).toString();
    }

    @Override
    public String nextQuestion(Long questionId) {
        Long listSize = questionCacheManager.getListSize();
        if (listSize == null || listSize <= 0) {
            questionCacheManager.refreshCache();
        }
        return questionCacheManager.nextQuestion(questionId).toString();
    }

    private void refreshQuestion() {
        List<Question> questionList = questionMapper.selectList(new LambdaQueryWrapper<Question>());
        if (CollectionUtil.isEmpty(questionList)) {
            return;
        }
        List<QuestionES> questionESList = BeanUtil.copyToList(questionList, QuestionES.class);
        questionRepository.saveAll(questionESList);
    }
    
    @Override
    public List<QuestionVO> hotList() {
        // 先从Redis获取热门题目列表
        List<Long> questionIds = redisService.getCacheListByRange(HOT_QUESTION_KEY, 0, 9, Long.class);
        
        // 如果Redis中没有数据，从数据库查询并缓存
        if (CollectionUtil.isEmpty(questionIds)) {
            questionIds = userSubmitMapper.selectHostQuestionList();
            if (CollectionUtil.isNotEmpty(questionIds)) {
                // 缓存热门题目列表
                redisService.rightPushAll(HOT_QUESTION_KEY, questionIds);
                // 设置过期时间
                redisService.expire(HOT_QUESTION_KEY, hotQuestionCacheTime, TimeUnit.MINUTES);
            } else {
                return Collections.emptyList();
            }
        }
        
        // 确保最多返回10条数据
        if (questionIds.size() > 10) {
            questionIds = questionIds.subList(0, 10);
        }
        
        // 检查ES中是否有数据，如果没有则刷新
        long count = questionRepository.count();
        if (count <= 0) {
            refreshQuestion();
        }
        
        // 从ES中获取题目详情
        List<QuestionVO> result = new ArrayList<>();
        for (Long id : questionIds) {
            QuestionES questionES = questionRepository.findById(id).orElse(null);
            // 如果ES中没有找到，尝试从MySQL查询并保存到ES
            if (questionES == null) {
                Question question = questionMapper.selectById(id);
                if (question != null) {
                    // 单个题目保存到ES
                    QuestionES newQuestionES = new QuestionES();
                    BeanUtil.copyProperties(question, newQuestionES);
                    questionRepository.save(newQuestionES);
                    
                    // 转换为VO对象
                    QuestionVO vo = new QuestionVO();
                    BeanUtil.copyProperties(newQuestionES, vo);
                    result.add(vo);
                }
            } else {
                // ES中有数据，直接转换为VO对象
                QuestionVO vo = new QuestionVO();
                BeanUtil.copyProperties(questionES, vo);
                result.add(vo);
            }
        }
        
        return result;
    }
}
